package com.wjh.anyview.quartz.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wjh.anyview.dao.ExamMapper;
import com.wjh.anyview.entity.po.Exam;
import com.wjh.anyview.service.ExamService;
import com.wjh.anyview.service.constant.ExamStatusConstant;
import com.wjh.anyview.util.SpringUtil;
import com.wjh.anyview.websocket.entity.bo.TopicMessage;
import com.wjh.anyview.websocket.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 结束考试的任务
 *
 * @author wjh
 * @date 2021/10/22 21:27
 * @Package com.wjh.anyview.quartz.job
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
@Slf4j
@Component
public class EndExamJob extends QuartzJobBean {

    private final StringRedisTemplate redisTemplate = SpringUtil.getBean("getRedisTemplate");

    private final ExamService examService = SpringUtil.getBean("examServiceImpl");

    private final ExamMapper examMapper = SpringUtil.getBean("examMapper");

    @Override
    protected void executeInternal(JobExecutionContext context) {
        QueryWrapper<Exam> wrapper = new QueryWrapper<>();
        //查询正在进行中的考试
        wrapper.eq("status", ExamStatusConstant.IN_PROGRESS);
        //当结束时间小于等于当前时间就结束考试
        wrapper.le("end_time", System.currentTimeMillis() / 1000);
        List<Exam> examList = examMapper.selectList(wrapper);
        examList.forEach(nowExam -> {
            Exam examUpdate = new Exam();
            examUpdate.setId(nowExam.getId());
            //设置考试状态为已经结束
            examUpdate.setStatus(ExamStatusConstant.END);
            //更新考试状态
            examMapper.updateById(examUpdate);

            //获取需要考这个试的学号
            List<String> numList = examService.listNumByExamId(nowExam.getId());
            //以当前毫秒时间戳作为redis中value的key
            String key = String.valueOf(System.currentTimeMillis());
            //redis中存放numList
            String numListString = numList.toString();
            String nums = numListString.substring(1, numListString.length() - 1);
            redisTemplate.opsForValue().set(key, nums);
            TopicMessage topicMessage = new TopicMessage();
            topicMessage.setMessage("考试结束，请停止答题！");
            topicMessage.setKey(key);

            //向频道发送信息
            redisTemplate.convertAndSend("TOPIC_EXAM", SecurityUtil.getTopicMessage(topicMessage));
        });
        //考试时间已经结束了

    }

}
